package io.renren.modules.nuaa.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.nuaa.dao.TCertificateDao;
import io.renren.modules.nuaa.dao.TQuestionAnswerDao;
import io.renren.modules.nuaa.dao.TQuestionItemDao;
import io.renren.modules.nuaa.dao.TUserDao;
import io.renren.modules.nuaa.dto.TQuestionItemDTO;
import io.renren.modules.nuaa.entity.TCertificateEntity;
import io.renren.modules.nuaa.entity.TQuestionAnswerEntity;
import io.renren.modules.nuaa.entity.TQuestionItemEntity;
import io.renren.modules.nuaa.entity.TUserEntity;
import io.renren.modules.nuaa.service.TQuestionItemService;
import io.renren.modules.nuaa.service.TUserService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

/**
 * 题目
 *
 * @author whc 15953295779@126.com
 * @since 3.0 2023-11-03
 */
@Service
public class TQuestionItemServiceImpl extends CrudServiceImpl<TQuestionItemDao, TQuestionItemEntity, TQuestionItemDTO> implements TQuestionItemService {

    @Autowired
    private TQuestionAnswerDao tQuestionAnswerDao;
    @Autowired
    private TCertificateDao tCertificateDao;
    @Autowired
    private TUserDao tUserDao;
    @Autowired
    private TQuestionItemDao tQuestionItemDao;

    @Override
    public QueryWrapper<TQuestionItemEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<TQuestionItemEntity> wrapper = new QueryWrapper<>();
        String questionId = (String)params.get("question_id");
        if(questionId != null){
            wrapper.eq("question_id", questionId);
        }
        return wrapper;
    }

    /**
     * 保存答案
     * @param id  问卷id
     * @param answerMap 选项
     * @param userId 用户id
     */
    @Override
    @Transactional
    public void submitAnswer(String id, Map answerMap, int userId) {
        // int userId = 1;
        List<TQuestionItemEntity> itemList = tQuestionItemDao.selectList(new QueryWrapper<TQuestionItemEntity>()
                .eq("question_id", id)
        );
        int totalScore = 0;
        TQuestionAnswerEntity answerEntity = new TQuestionAnswerEntity();
        for(TQuestionItemEntity item : itemList){
            String itemId = item.getId().toString();
            // 标准答案 A,B,C,D
            String standard = item.getStandard();
            // 分数
            int score = item.getScore();
            // 用户答案 B,D
            String answer = (String)answerMap.get(itemId);
            if(checkAnswer(answer, standard)) {
                totalScore += score;
            }else{
                item.setScore(0);
            }
            answerEntity = new TQuestionAnswerEntity();
            answerEntity.setQuestionId(item.getId().intValue());
            answerEntity.setAnswer(answer);
            answerEntity.setUserId(userId);
            answerEntity.setCreateAt(new Date());
            tQuestionAnswerDao.insert(answerEntity);
        }
        System.out.println("总分：" + totalScore);
        // 总分90可以生成证书
        if(totalScore >= 20){
            // 生成证书
            TUserEntity userEntity = tUserDao.selectById(userId);
            TCertificateEntity certificateEntity = new TCertificateEntity();
            certificateEntity.setName(userEntity.getRealName());
            certificateEntity.setIdCard(userEntity.getIdCard());
            // 证书编号生成逻辑：取系统时间到秒
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String no = sdf.format(new Date());
            //7空天少年
            certificateEntity.setCategoryId(7);
            certificateEntity.setCertificateNo(no);
            certificateEntity.setCreateDate(new Date());
            Calendar calendar = Calendar.getInstance();
            // 增加一年
            calendar.add(Calendar.YEAR, 1);
            // 获取增加一年后的时间
            Date newDate = calendar.getTime();
            certificateEntity.setExpirationDate(newDate);
            tCertificateDao.insert(certificateEntity);
        }
    }

    /**
     * 判断是否正确
     * @param answer 用户答案
     * @param dbAnswer 标准答案
     * @return
     */
    public static boolean checkAnswer(String answer, String dbAnswer){
        if(answer == null || dbAnswer == null){
            return false;
        }
        String[] answerArray = answer.split(",");
        String[] dbAnswerArray = dbAnswer.split(",");
        Arrays.sort(answerArray);
        Arrays.sort(dbAnswerArray);
        return Arrays.equals(answerArray, dbAnswerArray);
    }

    public static void main(String args[]) {
       boolean result =  TQuestionItemServiceImpl.checkAnswer("B,C,D", "B,D,A,C");
        if (result) {
            System.out.println("两个数组中的元素值相同");
        } else {
            System.out.println("两个数组中的元素值不相同");
        }
        String answers = "[{\"key\":\"answer-1-2\",\"val\":\"2\"},{\"key\":\"answer-2-5\",\"val\":\"5\"},{\"key\":\"answer-2-6\",\"val\":\"6\"}]";
        System.out.println("answers=" + answers);
        // string字符串转json对象
        JSONArray jsonArray = JSONArray.parseArray(answers);
        // json对象转java对象
        List<Map> list = jsonArray.toJavaList(Map.class);
        Map answerMap = new HashMap();
        for(Map map : list){
            //System.out.println(map.get("key"));
            //System.out.println(map.get("val"));
            String key = (String)map.get("key");
            String val = (String)map.get("val");
            String[] keyArray = key.split("-");
            String mval = (String)answerMap.get(keyArray[1]);
            if(mval == null) {
                answerMap.put(keyArray[1], val);
            }else{
                answerMap.put(keyArray[1], mval + "," + val);
            }
        }
        // Map转json字符串
        String jsonStr = JSONObject.toJSONString(answerMap);
        System.out.println("jsonStr=" + jsonStr);
    }

    @Override
    public Map rebuildAnswer(String answers) {
        JSONArray jsonArray = JSONArray.parseArray(answers);
        // json对象转java对象
        List<Map> list = jsonArray.toJavaList(Map.class);
        Map answerMap = new HashMap();
        for (Map map : list) {
            String key = (String) map.get("key");
            String val = (String) map.get("val");
            String[] keyArray = key.split("-");
            String mval = (String) answerMap.get(keyArray[1]);
            if (mval == null) {
                answerMap.put(keyArray[1], val);
            } else {
                answerMap.put(keyArray[1], mval + "," + val);
            }
        }
        return answerMap;
    }

    @Override
    public void saveTQuestionItem(TQuestionItemEntity tQuestionItemEntity) {
        baseDao.insert(tQuestionItemEntity);
    }

    @Override
    public List<TQuestionItemEntity> selectByQuestionId(Long id) {

        List<TQuestionItemEntity> tQuestionItemEntityList = baseDao.selectList(new QueryWrapper<TQuestionItemEntity>().eq("question_id", id));

        return tQuestionItemEntityList;
    }


}